<?php

/**
 * alltosun.com 数据统计widget
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 高昂 (gaoa@alltosun.com) $
 * $Date: 2016-4-6 下午6:03:47 $
 * $Id: $
 */
class data_widget
{
    private $col_arr = array(
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
        'AA',
        'AB',
        'AC',
        'AD',
        'AE',
        'AF',
        'AG',
        'AH',
        'AI',
        'AJ',
        'AK',
        'AL',
        'AM',
        'AN'
    );
    private static $set_up_time = '2016-02-18 23:59:59';
    private $enable_user_ids = array();
    private $enable_store_ids = array();
    private $dir = '';
    private $path = '';
    private $time_to_run = '';

    public function __construct() {
        $this->dir = EXPORT_PATH;
    }


    /**
     * worksheet(工作表)和title_list(标题)和data_list(数据)的个数一一对应
     */
    public function export_list($is_export) {
        //var_dump($is_export);
        //var_dump('export_list');
        // set_time_limit(60);

        $this->enable_user_ids = _model('user')->getFields('id', array(
            'is_enable' => 1,
            'status' => 1,
            '`add_time` <= ' => date('Y-m-d', $this->time_to_run) . ' 23:59:59'
        ));
        $this->enable_store_ids = _model('store')->getFields('id', array(
            'is_enable' => 1,
            'is_delete' => 1,
            '`add_time` <= ' => date('Y-m-d', $this->time_to_run) . ' 23:59:59'
        ));

        $file_name = Request::getParam('file_name', 'tongji_' . date('Ymd', $this->time_to_run) . '_');
        $worksheet_list = array(
            '合伙人&掌柜版订单统计',
            '合伙人明细',
            '掌柜明细',
            '设备绑定明细'
        );
        $title_list = array(
            array(
                // 属性
                'property' => array(
                    'text_align' => 'center',
                    'font_size' => '20', // 字体大小
                    'font_weight' => 'bold', // 字体粗细
                    // 'font_family' => '微软雅黑', // 字体
                    'color' => 'black', // 字体颜色
                    // 'width' => '', // 单元格宽度
                    // 'height' => '', // 单元格高度
                    // 'colspan'        => 1, // 合并几列
                    // 'rowspan'        => 1, // 合并几行
                ),
                'dealer' => array(
                    'title' => '合伙人APP安装以及订单统计',
                    'content' => array(
                        'property' => array(
                            'font_size' => 11,
                            'font_weight' => 'bold',
                            'colspan' => 9,
                            'rowspan' => 1
                        ),
                        'date' => array('title' => '日期'),
                        'today_add_dealer_num' => array('title' => '合伙人今日新增APP'),
                        'today_dealer_new_order_num' => array('title' => '新增订单'),
                        'today_dealer_cancel_order_num' => array('title' => '撤销订单'),
                        'prepare_delivery_order_num' => array('title' => '待发货订单'),
                        'today_dealer_order_num' => array('title' => '订单总数'),
                        'delivery_goods_num' => array('title' => '已出货'),
                        'prepare_delivery_goods_num' => array('title' => '待发货'),
                        'is_create_stock_person_num' => array('title' => '创建库存(人)'),
                        'not_create_stock_person_num' => array('title' => '未创建库存(人)'),
                        'all_dealer_stock' => array('title' => '合伙人总库存'),
                        'marketing_num' => array('title' => '总员工数'),
                        'dealer_num' => array('title' => '合伙人APP总数'),
                    ),
                ),
                'store' => array(
                    'title' => '掌柜版APP安装以及订单统计',
                    'content' => array(
                        'property' => array(
                            'background_color' => 'FF92D050', // 单元格的背景色(设置母标题背景色)
                            'font_weight' => 'bold',
                            'font_size' => 11,
                            'colspan' => 11,
                            'rowspan' => 1,
                        ),
                        'today_add_store_num' => array('title' => '今日新增掌柜版APP'),
                        'dealer_sign_store_num' => array('title' => '合伙人签约'),
                        'marketing_sign_store_num' => array('title' => '员工签约'),
                        'trial_store_num' => array('title' => '未审核'),
                        'normal_store_num' => array('title' => '正常营业'),
                        'stop_store_num' => array('title' => '撤店'),
                        'is_stock_store_num' => array('title' => '已进货门店'),
                        'not_stock_store_num' => array('title' => '未进货门店'),
                        'store_new_order_num' => array('title' => '新增订单'),
                        'today_store_cancel_order_num' => array('title' => '撤销订单'),
                        'today_store_order_num' => array('title' => '订单总数'),
                        'store_num' => array('title' => '掌柜版APP总数'),
                    ),
                ),
            ),
            array(
                array(
                    'property' => array(
                        'font_size' => 11,
                        'font_weight' => 'bold',
                    ),
                    /**
                     * 日期    新增合伙人姓名    电话    是否创建库存    是否创建员工    员工数量    是否创建掌柜    掌柜数量    绑定设备数量    是否下单    下单数量    待收款    待配送    配送中    配送完成    撤销订单    撤销原因
                     * 绑定设备数量    自己下单    已经收到款就算                        没有
                     */
                    'add_time' => array('title' => '日期'),
                    'dealer_id' => array('title' => '合伙人ID'),
                    'dealer_name' => array('title' => '新增合伙人姓名'),
                    'dealer_mobile' => array('title' => '电话'),
                    'is_create_stock' => array('title' => '是否创建库存'),
                    'is_sign_marketing' => array('title' => '是否创建员工'),
                    'marketing_num' => array('title' => '员工数量'),
                    'is_sign_store' => array('title' => '是否创建掌柜'),
                    'store_num' => array('title' => '掌柜数量'),
                    'bind_device_num' => array('title' => '绑定设备数量'),
                    'is_ever_order_goods' => array('title' => '是否下单'),
                    'dealer_order_num' => array('title' => '下单数量'),
                    'prepare_pay_order_num' => array('title' => '待收款'),
                    'prepare_delivery_order_num' => array('title' => '待配送'),
                    'in_delivery_order_num' => array('title' => '配送中'),
                    'finish_delivery_order_num' => array('title' => '配送完成'),
                    'dealer_cancel_order_num' => array('title' => '撤销订单'),
                )
            ),
            array(
                array(
                    'property' => array(
                        'font_size' => 11,
                        'font_weight' => 'bold',
                    ),
                    'id' => array('title' => '店铺id'),
                    'store_title' => array('title' => '店铺名称'),
                    'store_type' => array('title' => '门店类型'),
                    'add_time' => array('title' => '添加时间'),
                    'store_status' => array('title' => '门店状态'),
                    'sign_user' => array('title' => '签约人(角色)'),
                    'dealer_name' => array('title' => '所属合伙人'),
                    'is_ever_stock' => array('title' => '是否进过货'),
                    'stock_num' => array('title' => '进货数量'),
                    'is_bind_device' => array('title' => '是否绑定设备')
                )
            ),
            array(
                'property' => array(),
                'machine' => array(
                    'title' => '保温箱',
                    'content' => array(
                        'property' => array(),
                        'machine_add_time' => array('title' => '日期'),
                        'machine_device_no' => array('title' => '序列号'),
                        'machine_status' => array('title' => '状态'),
                        'machine_store_name' => array('title' => '绑定门店'),
                        'machine_dealer_name' => array('title' => '所属合伙人'),
                        'machine_bind_time' => array('title' => '绑定时间'),
                    ),
                ),
                'adbox' => array(
                    'title' => '广告机',
                    'content' => array(
                        'property' => array(),
                        'adbox_add_time' => array('title' => '日期'),
                        'adbox_device_no' => array('title' => '序列号'),
                        'adbox_status' => array('title' => '状态'),
                        'adbox_store_name' => array('title' => '绑定门店'),
                        'adbox_dealer_name' => array('title' => '所属合伙人'),
                        'adbox_bind_time' => array('title' => '绑定时间'),
                    ),
                )
            )
        );

        // 数据列表
        $data_list = array(
            array(
                //获取经销商订单信息
                'data' => $this->get_dealer_store_list(),
            ),
            array(
                //获取合伙人明细
                'data' => $this->get_dealer_info_list($this->time_to_run),
            ),
            array(
                //获取商家明细
                'data' => $this->get_store_data_list($this->time_to_run),
            ),
            array(
                //获取设备绑定信息
                'data' => $this->get_device_record_list($this->time_to_run),
            ),
        );

        // 执行导出execl
        return $this->exec_export($file_name, $worksheet_list, $title_list, $data_list, $is_export);

    }


    /**
     * 获取合伙人明细
     */
    public function get_dealer_info_list($time = '') {

        if (!$time) {
            $time = strtotime('-1 day');
        }

        $data_list = _uri('admin_dealer_store_device_data_day', array('date' => date('Y-m-d', $time)), 'dealer_data');
        $dealer_list = json_decode($data_list, true);
        return $dealer_list;
    }

    /**
     * 获取商家明细
     */
    public function get_store_data_list($time = '') {

        if (!$time) {
            $time = strtotime('-1 day');
        }
        $data_list = _uri('admin_dealer_store_device_data_day', array('date' => date('Y-m-d', $time)), 'store_data');

        $store_list = json_decode($data_list, true);
        return $store_list;
    }

    /**
     * 获取经销商订单信息
     */
    private function get_dealer_store_list() {
        // 先执行添加记录操作
        // _widget('admin_data.data')->save_dealer_store_data();

        $data_list = array();
        // 只导出昨天的
        $data_list = _model('admin_dealer_store_data_day')->getList(array(1 => 1), ' ORDER BY `id` DESC LIMIT 0, 1');
        if (!$data_list) {
            // $set_up_time = '2016-02-18 15:55:00';
            $set_up_time = '2016-02-18 23:59:59';
            $data_list = array();
            $time = strtotime($set_up_time);
            for ($i = 0, $cur_time = $time; date('Ymd', $cur_time) < date('Ymd'); $i++) {
                $cur_time = strtotime('+' . $i . ' day', $time);
                array_push($data_list, admin_data_helper::get_admin_data($cur_time));
            }
        }

        return $data_list;
    }


    /**
     * 获取设备绑定信息
     */
    public function get_device_record_list($time = '') {

        if (!$time) {
            $time = strtotime('-1 day');
        }
        $data_list = _uri('admin_dealer_store_device_data_day', array('date' => date('Y-m-d', $time)), 'device_data');
        $device_list = json_decode($data_list, true);

        return $device_list;

    }


    /**
     * 执行导出execl
     * @param $file_name 文件名
     * @param $export_list 数据列表
     */
    private function exec_export($file_name, $worksheet_list, $title_list, $data_list, $is_export) {
        if (!$file_name || !$worksheet_list || !$title_list || !$data_list) {
            return false;
        }

        //初始化excel对象
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);

        $objPHPExcel->getDefaultStyle()->getFont()->setName('宋体');
        // 建立循环索引
        $k = 0;
        foreach ($worksheet_list as $worksheet) {

            if ($k) {
                //添加一个新的worksheet
                $objPHPExcel->createSheet();
            }
            // 设置工作表名称
            $objPHPExcel->getSheet($k)->setTitle($worksheet);
            $start_row = 1;
            // 统计需要多少列
            $col_num = 0;
            $col_title_alias_arr = array();
            $col_title_arr = array();
            if (count($title_list[$k]) > 1) {
                foreach ($title_list[$k] as $kk => $v) {
                    if ($kk == 'property') {
                        continue;
                    }

                    $col_num += count($title_list[$k][$kk]['content']) - 1;

                    array_push($col_title_alias_arr, array_slice(array_keys($v['content']), 1));
                    foreach ($v['content'] as $kkk => $vv) {
                        if ($kkk == 'property') {
                            continue;
                        }
                        array_push($col_title_arr, $vv['title']);
                    }
                }
                $start_row = 2;

            } else {
                $col_num = count($title_list[$k][0]) - 1;
                $col_title_alias_arr = array_slice(array_keys($title_list[$k][0]), 1);
                foreach ($title_list[$k][0] as $kkk => $vv) {
                    if ($kkk == 'property') {
                        continue;
                    }
                    array_push($col_title_arr, $vv['title']);
                }
                $start_row = 1;
            }
            $col_arr = array_slice($this->col_arr, 0, $col_num);

            // 设置单元格属性
            if ($start_row == 2 && 0 == $k) {
                // 合并单元格
                $objPHPExcel->getSheet($k)->mergeCells("A1:M1");
                $objPHPExcel->getSheet($k)->mergeCells("N1:Y1");

                // 设置单元格的高度
                $objPHPExcel->getSheet($k)->getRowDimension(1)->setRowHeight(35);
                //设置单位格内容
                $objPHPExcel->getSheet($k)->setCellValue('A1', $title_list[0]['dealer']['title']);
                $objPHPExcel->getSheet($k)->setCellValue('N1', $title_list[0]['store']['title']);
                //格式化数字为字符串，避免导致数字默认右对齐单元格
                // $objPHPExcel->getSheet($k)->getStyle('A1')->getNumberFormat()->setFormatCode("@");
                // $objPHPExcel->getSheet($k)->getStyle('M1')->getNumberFormat()->setFormatCode("@");
                //设置自动换行
                $objPHPExcel->getSheet($k)->getStyle('A1')->getAlignment()->setWrapText(true);
                $objPHPExcel->getSheet($k)->getStyle('N1')->getAlignment()->setWrapText(true);
                // 标题字体加粗
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFont()->setBold(true);
                $objPHPExcel->getSheet($k)->getStyle('N1')->getFont()->setBold(true);
                // 设置字体大小
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFont()->setSize(20);
                $objPHPExcel->getSheet($k)->getStyle('N1')->getFont()->setSize(20);
                // 设置字体居中
                //设置对齐方式
                $objPHPExcel->getSheet($k)->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle('N1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle('N1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

                // 设置填充颜色
                //设置填充颜色
                $objPHPExcel->getSheet($k)->getStyle('N1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                $objPHPExcel->getSheet($k)->getStyle('N1')->getFill()->getStartColor()->setARGB('FF00B0F0');
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFill()->getStartColor()->setARGB('FF92D050');

            } elseif (3 == $k) {
                // 合并单元格
                $objPHPExcel->getSheet($k)->mergeCells("A1:F1");
                $objPHPExcel->getSheet($k)->mergeCells("G1:L1");

                // 设置单元格的高度
                $objPHPExcel->getSheet($k)->getRowDimension(1)->setRowHeight(35);
                //设置单位格内容
                $objPHPExcel->getSheet($k)->setCellValue('A1', $title_list[3]['machine']['title']);
                $objPHPExcel->getSheet($k)->setCellValue('G1', $title_list[3]['adbox']['title']);
                //格式化数字为字符串，避免导致数字默认右对齐单元格
                // $objPHPExcel->getSheet($k)->getStyle('A1')->getNumberFormat()->setFormatCode("@");
                // $objPHPExcel->getSheet($k)->getStyle('L1')->getNumberFormat()->setFormatCode("@");
                //设置自动换行
                $objPHPExcel->getSheet($k)->getStyle('A1')->getAlignment()->setWrapText(true);
                $objPHPExcel->getSheet($k)->getStyle('G1')->getAlignment()->setWrapText(true);
                // 标题字体加粗
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFont()->setBold(true);
                $objPHPExcel->getSheet($k)->getStyle('G1')->getFont()->setBold(true);
                // 设置字体大小
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFont()->setSize(20);
                $objPHPExcel->getSheet($k)->getStyle('G1')->getFont()->setSize(20);
                // 设置字体居中
                //设置对齐方式
                $objPHPExcel->getSheet($k)->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle('G1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle('G1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

                // 设置填充颜色
                //设置填充颜色
                $objPHPExcel->getSheet($k)->getStyle('G1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                $objPHPExcel->getSheet($k)->getStyle('G1')->getFill()->getStartColor()->setARGB('FF00B050');
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                $objPHPExcel->getSheet($k)->getStyle('A1')->getFill()->getStartColor()->setARGB('FF00B0F0');
            }

            $i = 0;
            // 设置文档属性
            foreach ($col_arr as $key => $val) {
                //设置列的宽度
                if (0 == $k) {
                    if (in_array($val, array('T', 'H', 'I', 'J', 'K', 'M', 'Y'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(15);
                    } elseif (in_array($val, array('B', 'M', 'N'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(20);
                    } elseif (in_array($val, array('A', 'G'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(12);
                    } else {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(10);
                    }
                } elseif (1 == $k) {
                    if (in_array($val, array('A', 'C', 'D'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(20);
                    } elseif (in_array($val, array('E', 'F', 'H', 'J'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(12);
                    } else {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(10);
                    }
                } elseif (2 == $k) {
                    if (in_array($val, array('B', 'C', 'D', 'F'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(22);
                    } elseif (in_array($val, array('A'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(8);
                    } else {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(12);
                    }
                } else {
                    if (in_array($val, array('C', 'E', 'I', 'K'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(10);
                    } elseif (in_array($val, array('A', 'G'))) {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(15);
                    } else {
                        $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(22);
                    }
                }

                // $objPHPExcel->getSheet($k)->getColumnDimension($val)->setWidth(12);
                //自动设置单元格宽度   例：
                // $objPHPExcel->getSheet($k)->getColumnDimension($val)->setAutoSize(true);
                //设置单位格内容
                $objPHPExcel->getSheet($k)->setCellValue($val . $start_row, $col_title_arr[$key]);
                //格式化数字为字符串，避免导致数字默认右对齐单元格
                $objPHPExcel->getSheet($k)->getStyle($val)->getNumberFormat()->setFormatCode("@");
                //设置自动换行
                $objPHPExcel->getSheet($k)->getStyle($val)->getAlignment()->setWrapText(true);
                // 标题字体加粗
                $objPHPExcel->getSheet($k)->getStyle($val . $start_row)->getFont()->setBold(true);
                //设置对齐方式
                $objPHPExcel->getSheet($k)->getStyle($val)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle($val .
                                                     $start_row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle($val)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $objPHPExcel->getSheet($k)->getStyle($val .
                                                     $start_row)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

                // 设置边框
                if ($k == 0) {
                    $objPHPExcel->getSheet($k)->getStyle($val .
                                                         $start_row)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $objPHPExcel->getSheet($k)->getStyle($val .
                                                         $start_row)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
                    $objPHPExcel->getSheet($k)->getStyle($val .
                                                         $start_row)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $objPHPExcel->getSheet($k)->getStyle($val .
                                                         $start_row)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                }

                $i++;
                if ($start_row == 2) {
                    // 设置背景色
                    //设置填充颜色
                    //                     if ($i > 9 && 0 == $k) {
                    //                         $objPHPExcel->getSheet($k)->getStyle($val.$start_row)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                    //                         $objPHPExcel->getSheet($k)->getStyle($val.$start_row)->getFill()->getStartColor()->setARGB('FF92D050');
                    //                     }

                    // 设置完成后冻结行(冻结前两行则设置为A3(只冻结行))
                    $objPHPExcel->getSheet($k)->freezePane('A3');
                } else {
                    // 必须在设置完值之后才可以
                    $objPHPExcel->getSheet($k)->freezePane('A2');
                }
            }
            $start_row++;

            if (isset($col_title_alias_arr[1]) && is_array($col_title_alias_arr[1])) {
                $col_title_alias_arr = array_merge($col_title_alias_arr[0], $col_title_alias_arr[1]);
            }
            foreach ($data_list[$k]['data'] as $data_key => $val) {
                foreach ($col_arr as $col_key => $col) {
                    $place = $col . $start_row;
                    $col_content = $col_title_arr[$col_key];

                    $value = '';

                    $val_keys = @array_keys($val) ? array_keys($val) : array();
                    if (in_array($col_title_alias_arr[$col_key], $val_keys)) {
                        $value = $val[$col_title_alias_arr[$col_key]];
                    }

                    $objPHPExcel->getSheet($k)->setCellValue($place, $value);

                }
                $start_row++;
            }

            $k++;
        }

        //设置当前的sheet索引
        $objPHPExcel->setActiveSheetIndex(0);

        $title = trim($file_name) . date('YmdHis') . ".xls";

        if ($is_export) {
            //设置页面类型
            header("Content-Type: application/vnd.ms-excel");
            //用于下载的文件头
            header("Content-Type: application/force-download");
            header("Content-Type: application/download");
            header("Content-Type: application/octet-stream");

            // ff正常，ie不正常，下面是从网站找到的解决方案
            if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
                $title = rawurlencode($title);
            }
            header("Content-Disposition: attachment; filename=" . $title);
            header("Content-Transfer-Encoding: binary");
            //最后修改时间
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            //不使用缓存
            header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
            header('Cache-Control: public');
            header("Expires: 0");
            header("Pragma: public");
            $objWriter->save('php://output');
            exit;
        } else {
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $this->path = $this->dir . $title;
            $objWriter->save($this->path);
        }
        //         $objWriter->save('/data/svn_data/outsourcing2014/web/baobaotang/web/excel/'.$title);
    }


    /**
     *
     * 存入数据表
     */
    public function save_dealer_store_data($time) {
        if (!$time) {
            $time = strtotime('-1 day');
        }
        //var_dump('save_dealer_store_data');
        $data_list = admin_data_helper::get_admin_data($time);

        $date = date('Y-m-d', strtotime($data_list['add_time']));

        $list = array();
        $list['day'] = $data_list;
        $list['week'] = $data_list;
        $list['month'] = $data_list;
        $list['day']['date'] = $this->get_date('day', $time);
        $list['week']['date'] = $this->get_date('week', $time);
        $list['month']['date'] = $this->get_date('month', $time);

        foreach ($list as $k => $v) {
            $data_info = _uri('admin_dealer_store_data_' . $k, array('date' => $list[$k]['date']));
            if ($data_info) {
                // 更新
                //_model('admin_dealer_store_data_'.$k)->update($data_info['id'], $v);
            } else {
                // 添加
                _model('admin_dealer_store_data_' . $k)->create($v);
            }
        }

        // 存入合伙人,门店,设备绑定统计信息表
        $dealer_data_list = admin_data_helper::get_dealer_info_list($time);
        $store_data_list = admin_data_helper::get_store_data_list($time);
        $device_data_list = admin_data_helper::get_device_record_list($time);
        $data = array();
        $data['dealer_data'] = json_encode($dealer_data_list);
        $data['store_data'] = json_encode($store_data_list);
        $data['device_data'] = json_encode($device_data_list);
        $data['date'] = $this->get_date('day', $time);
        $data['add_time'] = date('Y-m-d H:i:s');

        //改造
        $info = _uri('admin_dealer_store_device_data_day', array('date' => $data['date']));
        if ($info) {
            // 更新
            _model('admin_dealer_store_device_data_day')->update($info['id'], $data);
        } else {
            // 添加
            _model('admin_dealer_store_device_data_day')->create($data);
        }
        //_widget('admin_data.data')->export_list_email();
        // 给自己发一封邮件
        //_widget('email')->mail(email_config::$coder_email_list, '抱抱堂运营数据', '昨天数据已保存!', '');

        /*
            _widget('admin_data.data')->export_list(0);
        //var_dump('export');


            // 给客户发一封
            if (ONDEV) {
                _widget('email')->mail(email_config::$coder_email_list, '抱抱堂运营数据', '数据见附件', $this->path);
            } else {
                _widget('email')->mail(email_config::$user_email_list, '抱抱堂运营数据', '数据见附件', $this->path);
            }
        */

    }

    /**
     * 导出excel发送邮件
     */
    public function export_list_email($time = '') {
        $this->time_to_run = $time;
        if (!$this->time_to_run) {
            $this->time_to_run = strtotime('-1 day');
        }
        // 导出
        _widget('admin_data.data')->export_list(0);
        $url = STATIC_URL . '/images/data/' . basename($this->path);
        // 给客户发一封
        if (ONDEV) {
            _widget('email')->mail(email_config::$coder_email_list, '抱抱堂运营数据', '下载地址： ' . $url);
        } else {
            _widget('email')->mail(email_config::$user_email_list, '抱抱堂运营数据', '下载地址： ' . $url);
        }
    }
    /*
    public function export_list_email2()
    {
        // 导出
        _widget('admin_data.data')->export_list(0);

        // 给客户发一封
        if (ONDEV) {
            _widget('email')->mail(email_config::$coder_email_list, '抱抱堂运营数据', '数据见附件', $this->path);
        } else {
            _widget('email')->mail(email_config::$user_email_list, '抱抱堂运营数据', '数据见附件', $this->path);
        }
    }*/

    /**
     * 按照时间返回对应的日，周，月，统计用
     * @param unknown_type $type
     * @param unknown_type $time
     * @return string
     */
    private function get_date($type, $time = '') {
        if (!$time) {
            $time = time();
        }

        if ($type == 'day') {
            $date = date('Y-m-d', $time);
        } else {
            if ($type == 'week') {
                // 第几周
                $date = strftime('%Y%W', $time);
            } else {
                if ($type == 'month') {
                    $date = date('Ym', $time);
                }
            }
        }
        return $date;
    }


}

?>
